package com.dayu.gulimall.ware.service.impl;

import com.dayu.common.constant.PurchaseConstant;
import com.dayu.gulimall.ware.entity.PurchaseDetailEntity;
import com.dayu.gulimall.ware.entity.WareSkuEntity;
import com.dayu.gulimall.ware.service.PurchaseDetailService;
import com.dayu.gulimall.ware.service.WareSkuService;
import com.dayu.gulimall.ware.vo.MergeVo;
import com.dayu.gulimall.ware.vo.PurchaseDoneVo;
import com.dayu.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayu.common.utils.PageUtils;
import com.dayu.common.utils.Query;

import com.dayu.gulimall.ware.dao.PurchaseDao;
import com.dayu.gulimall.ware.entity.PurchaseEntity;
import com.dayu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils unreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(PurchaseConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        List<Long> ids = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = ids.stream()
                .filter(id -> {
                    PurchaseDetailEntity detailEntity = purchaseDetailService.getById(id);
                    return detailEntity.getStatus() == PurchaseConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                            || detailEntity.getStatus() == PurchaseConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();
                }).map(i -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(i);
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setStatus(PurchaseConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

    }

    /**
     * 领取采购单
     *
     * @param ids 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        //确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(item -> {
            PurchaseEntity purchaseEntity = this.getById(item);
            return purchaseEntity;
        }).filter(item -> item.getStatus() == PurchaseConstant.PurchaseStatusEnum.CREATED.getCode()
                || item.getStatus() == PurchaseConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(purchaseEntity -> {
                    purchaseEntity.setStatus(PurchaseConstant.PurchaseStatusEnum.RECEIVED.getCode());
                    purchaseEntity.setUpdateTime(new Date());
                    return purchaseEntity;
                }).collect(Collectors.toList());

        //改变采购单状态
        this.updateBatchById(collect);
        //改变采购项状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listPurchaseDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> entities = detailEntities.stream().map(detail -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(detail.getId());
                detailEntity.setStatus(PurchaseConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(entities);
        });


    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 改变采购单状态
        Long id = purchaseDoneVo.getId();

        // 改变采购项状态
        List<PurchaseItemVo> items = purchaseDoneVo.getItems();
        boolean flag = true;
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for (PurchaseItemVo item : items) {
            if (item.getStatus() == PurchaseConstant.PurchaseStatusEnum.FAIL.getCode()) {
                flag = false;
            } else {
                //如果采购成功， 成功采购进行入库
                PurchaseDetailEntity entity= purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getWareId(),entity.getSkuId(),entity.getSkuNum());
            }
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            detailEntity.setStatus(item.getStatus());
            list.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(list);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? PurchaseConstant.PurchaseStatusEnum.COMPLETED.getCode() : PurchaseConstant.PurchaseStatusEnum.FAIL.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}